package com.msgserver.ejb.services;

import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.ejb.LocalBean;
import javax.ejb.PostActivate;
import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import com.msgserver.entity.Company;
import com.msgserver.entity.CompanyAdmin;
import com.msgserver.entity.Employee;
import com.msgserver.entity.EmployeeGroup;

/**
 * Session Bean implementation class CompanyService
 */
public @Stateless class CompanyService implements CompanyServiceLocal {

    /**
     * Default constructor. 
     */
	
	@PersistenceContext(unitName="MsgServer_JPA")
	private EntityManager em;
	protected transient Logger logger;
    public CompanyService() {
        // TODO Auto-generated constructor stub
    }
    
    @PostConstruct
    protected void init(){
    	initLogger();
    }
    
    @PostActivate
    protected void initLogger(){
    	if (logger == null) {
			logger = Logger.getLogger(this.getClass());
		}
    }

	@Override
	public CompanyAdmin getCompanyAdminByLoginAndPassword(String login,
			String pwd) {
		String query = "select c from CompanyAdmin c left join fetch c.company cc left join fetch cc.groups ccg left join fetch cc.contract left join fetch ccg.employee ccge left join fetch ccge.groups where c.login=:login and c.password=:pwd";
		try {
			return (CompanyAdmin) em.createQuery(query).setParameter("login", login).setParameter("pwd", pwd).getSingleResult();
		} catch (NoResultException e) {
			logger.debug("can not find admin ");
			return null;
		}
	}

	@Override
	public Set<Employee> loadEmpsByCompany(Company company) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Company> loadAllCompanies() {
		String query = "select c from Company c";
		try {
			return (List<Company>)em.createQuery(query).getResultList();
		} catch (Exception e) {
			logger.debug("no company is loaded");
			return null;
		}
		
	}

	@Override
	public Company persistCompany(Company company) {
		em.clear();
		return em.merge(company);
	}

	@Override
	public void deleteCompany(Company company) {
		Company companyTodel = em.find(Company.class,  company.getId());
		em.remove(companyTodel);
		
	}

	@Override
	public EmployeeGroup persistGroup(EmployeeGroup group) {
		return em.merge(group);
		
	}

	@Override
	public void deleteEmps(List<Employee> emps) {
		for(Employee emp:emps){
			Employee e = em.find(Employee.class, emp.getId());
			em.remove(e);
			em.flush();
		}
		
	}

	@Override
	public Company loadCompanyByName(String name) {
	//	String query = "select c from Company c left join fetch c.groups "
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> getEmpBySearchKeyWord(String key,  boolean isName) {
		if(isName){
			try {
				return (List<Employee>) em.createQuery("select e from Employee e where e.name=:name").setParameter("name", key).getResultList();
			} catch (NoResultException e) {
				return null;
			}
		}else{
			try {
				return (List<Employee>) em.createQuery("select e from Employee e where e.phoneNumber=:phoneNumber").setParameter("phoneNumber", key).getResultList();
			} catch (NoResultException e) {
				return null;
			}
		}
	}

	@Override
	public Employee updateEmp(Employee emp) {
		return em.merge(emp);
	}

}
